package com.helloandroid

import android.app.Application
import android.content.*
import android.os.*
import androidx.lifecycle.*
import com.helloandroid.ads.NativeAdUtil
import com.helloandroid.ads.ResumeAdUtil
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.app.model.UserViewModel
import com.helloandroid.ext.Json
import com.helloandroid.msg.MsgKey
import com.helloandroid.services.ServerService
import com.helloandroid.tools.*
import dai.android.util.AndroidUtils

data class SyncInfo(
        var needSync: Boolean = false,  // 是否需要同步
        var syncing: Boolean = false, // 是否是同步中
        var loginTime: Long = -1,// 登陆的时间
        var syncTime: Long = -1, // 下次应该同步的时间
) {
    fun updateLoginTime(time: Long) {
        loginTime = time
        syncTime = MyTimeUtils.getStartDayMs(time) + GUtils.OneDayMs
        syncing = false
        needSync = false
    }
}


class MyApplication : Application(), ViewModelStoreOwner {

    companion object{
        lateinit var app:MyApplication

        @JvmStatic
        fun getPerference(filename: String): SharedPreferences = app.getSharedPreferences(filename, Application.MODE_PRIVATE)
    }

    val myHandler = Handler(Looper.getMainLooper())
    var serverProxy: IBSService? = null

    private lateinit var mAppViewModelStore: ViewModelStore
    private lateinit var mFactory: ViewModelProvider.Factory

    val client = object : IClient.Stub() {
        override fun notifyClient(sysBs: Int): String {
            // 收到步数更新
            // 返回玩家最新的步数
            AppUtil.updateUserBs(sysBs)

            AppUtil.checkBsCompletion()

            // 将最新的玩家步数信息发送给服务端
            return Json {
                MsgKey.CurBs to AppUtil.user.bs
                MsgKey.SysBuShu to AppUtil.user.bs_sys
            }.toString()
        }
    }

    override fun onCreate() {
        super.onCreate()
        val processName = AndroidUtils.getCurrentProcessNameByAT()
        MyLog.elog("-----------------------------------------")
        MyLog.info("processName:$processName")
        app = this
        if (processName == packageName) {

            MyLog.info("主进程id:" + android.os.Process.myPid())
            MyLog.info("verison:${Build.VERSION.RELEASE}")

            AppUtil.initLocal(app)

            ResumeAdUtil.registResumeAd(this)

            // 启动且绑定服务
            c2sStartService()

            //  使用 applicationContext
            NativeAdUtil.initNativeAd()
            SmallNativeAdUtil.initNativeAd()
            VideoAdUtil.initVideoAd()
        } else {
            MyLog.elog("Service 进程Id:" + android.os.Process.myPid())

            AppUtil.initOthers(app)
        }

        // 全局  viewmodel
        mAppViewModelStore = ViewModelStore()
        mFactory = ViewModelProvider
                .AndroidViewModelFactory
                .getInstance(this)
    }

    override fun getViewModelStore(): ViewModelStore {
        return mAppViewModelStore
    }

    fun getUserViewModel() = ViewModelProvider(this, mFactory).get(UserViewModel::class.java)

    // 启动服务
    private fun c2sStartService(){
        val intent = Intent(applicationContext, ServerService::class.java)
        startService(intent)

        // 绑定服务
        bindService(intent, object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                AppUtil.app.serverProxy = IBSService.Stub.asInterface(service)
                MyLog.info("====== service 绑定成功!")
                AppUtil.app.serverProxy?.setClient(AppUtil.app.client)
                service?.linkToDeath(deathRecipient,0)
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                MyLog.info("onServiceDisconnected called! 一般不会调用!")
                AppUtil.app.serverProxy = null
            }
        }, Context.BIND_AUTO_CREATE)
    }

    val deathRecipient = object :IBinder.DeathRecipient{
        override fun binderDied() {
            MyLog.info("#### binderDied called!")
            if (serverProxy == null){
                return
            }
            serverProxy!!.asBinder().unlinkToDeath(this,0)
            serverProxy = null

            // 重新绑定
            c2sStartService()
        }
    }
}



